package com.hbnu.Util;

import com.hbnu.Pojo.User;
import com.hbnu.Service.Impl.UserServiceImpl;
import com.hbnu.Service.UserService;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@WebFilter("/*")
public class LoginFilter implements Filter {

    private UserService userService = new UserServiceImpl();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        User sessionUser = (User) request.getSession().getAttribute("session_user");

        Cookie cookie = CookieUtils.getCookieByCookieName("remember", request);

        String requestURI = request.getRequestURI();

        if (sessionUser != null){
            if (cookie != null) {
              if (requestURI.equals("/") || requestURI.equals("/login")) {
                  request.getSession().setAttribute("session_user", sessionUser);
                  request.getRequestDispatcher("/jsp/main.jsp").forward(servletRequest, servletResponse);

              }
              else {
                  filterChain.doFilter(servletRequest, servletResponse);

              }

            }
            else {
                filterChain.doFilter(servletRequest, servletResponse);
            }

        }
        else {
            if (cookie != null) {
                String cookieValue = cookie.getValue();
                String[] cookieInfo = cookieValue.split("#");

                User user = userService.findUserByStuCodeAdnPassword(cookieInfo[0], cookieInfo[1]);

                if (requestURI.equals("/") || requestURI.equals("/login")) {
                    request.getSession().setAttribute("session_user", user);
                    request.getRequestDispatcher("/jsp/main.jsp").forward(servletRequest, servletResponse);

                } else {
                    filterChain.doFilter(servletRequest, servletResponse);

                }
            } else {
//                if (requestURI.equals("/") || requestURI.equals("/login")) {
//                    filterChain.doFilter(servletRequest, servletResponse);
//
//                } else {
//                    request.setAttribute("error", "error");
//                    request.getRequestDispatcher("index.jsp").forward(servletRequest, servletResponse);
//
//                }

                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
